# 食物类别管理的视图文件
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.core.paginator import Paginator
from django.db.models import Q
from datetime import datetime

from django.urls import reverse

from myadmin.models import FoodCategories, Foods


# 食物类别管理
def index(request, pIndex=1):
    """类别列表页"""
    try:
        mod = FoodCategories.objects
        clist = mod.all()
        mywhere = []
        
        # 排序处理
        sort = request.GET.get('sort', 'category_id')  # 默认按ID排序
        order = request.GET.get('order', 'asc')
        valid_sorts = ['category_id', 'category_name', 'parent_id', 'description']
        
        # 验证排序字段有效性
        if sort not in valid_sorts:
            sort = 'category_id'
        # 处理排序方向
        sort_str = sort if order == 'asc' else f'-{sort}'
        clist = clist.order_by(sort_str)
        
        # 保存排序参数到mywhere
        mywhere.append(f'sort={sort}')
        mywhere.append(f'order={order}')
        
        # 搜索处理
        kw = request.GET.get("keyword", None)
        if kw:
            clist = clist.filter(category_name__contains=kw)
            mywhere.append(f'keyword={kw}')
        
        # 分页处理
        pIndex = int(pIndex)
        page = Paginator(clist, 5)  # 每页5条
        maxpages = page.num_pages
        
        # 页码越界处理
        if pIndex > maxpages:
            pIndex = maxpages
        if pIndex < 1:
            pIndex = 1
        
        list2 = page.page(pIndex)
        plist = page.page_range
        
        context = {
            "categorylist": list2,
            'plist': plist,
            'pIndex': pIndex,
            'maxpages': maxpages,
            'mywhere': mywhere,
            'sort': sort,  # 传递当前排序字段到模板
            'order': order  # 传递当前排序方向到模板
        }
        return render(request, "myadmin/foodcategories/index.html", context)
    except Exception as err:
        print(f"类别列表加载错误: {err}")
        context = {'info': "加载类别列表失败！"}
        return render(request, "myadmin/info.html", context)


def add(request):
    """加载类别添加表单"""
    try:
        parents = FoodCategories.objects.all()
        context = {'parents': parents}
        return render(request, "myadmin/foodcategories/add.html", context)
    except Exception as err:
        print(f"加载添加表单错误: {err}")
        context = {'info': "加载添加表单失败！"}
        return render(request, "myadmin/info.html", context)


def insert(request):
    """执行类别添加"""
    try:
        # 检查ID是否已存在
        cid = request.POST.get('category_id')
        if FoodCategories.objects.filter(category_id=cid).exists():
            return render(request, "myadmin/info.html", {'info': "添加失败：类别ID已存在！"})
        
        ob = FoodCategories()
        ob.category_id = cid
        ob.category_name = request.POST.get('category_name').strip()
        parent_id = request.POST.get('parent_id')
        ob.parent_id = FoodCategories.objects.get(category_id=parent_id) if parent_id else None
        ob.description = request.POST.get('description', '').strip()
        ob.save()
        return redirect(reverse('myadmin_foodcategories_index', args=[1]))
    except Exception as err:
        print(f"添加类别错误: {err}")
        context = {'info': "添加失败！"}
        return render(request, "myadmin/info.html", context)


def edit(request, cid=0):
    """加载类别编辑表单"""
    try:
        ob = FoodCategories.objects.get(category_id=cid)
        # 排除自身作为父类别选项
        parents = FoodCategories.objects.exclude(category_id=cid)
        context = {'category': ob, 'parents': parents}
        return render(request, "myadmin/foodcategories/edit.html", context)
    except FoodCategories.DoesNotExist:
        context = {'info': "编辑失败：类别不存在！"}
    except Exception as err:
        print(f"加载编辑表单错误: {err}")
        context = {'info': "加载编辑表单失败！"}
    return render(request, "myadmin/info.html", context)


def update(request, cid):
    """执行类别编辑"""
    try:
        ob = FoodCategories.objects.get(category_id=cid)
        ob.category_name = request.POST.get('category_name').strip()
        parent_id = request.POST.get('parent_id')
        
        # 防止选择自身作为父类别
        if parent_id == cid:
            return render(request, "myadmin/info.html", {'info': "修改失败：不能选择自身作为父类别！"})
        
        ob.parent_id = FoodCategories.objects.get(category_id=parent_id) if parent_id else None
        ob.description = request.POST.get('description', '').strip()
        ob.save()
        return render(request, "myadmin/info.html", {
            'info': "修改成功！",
            'redirect_url': reverse('myadmin_foodcategories_index', args=[1])
        })
    except FoodCategories.DoesNotExist:
        context = {'info': "修改失败：类别不存在！"}
    except Exception as err:
        print(f"修改类别错误: {err}")
        context = {'info': "修改失败！"}
    return render(request, "myadmin/info.html", context)


def delete(request, cid=0):
    """执行类别删除"""
    try:
        ob = FoodCategories.objects.get(category_id=cid)
        # 修复：使用related_name='children'检查子类别，而非foodcategories_set
        if ob.children.exists() or Foods.objects.filter(category=ob).exists():
            context = {'info': "删除失败：存在子类别或关联食物！"}
        else:
            ob.delete()
            context = {'info': "删除成功！"}
    except FoodCategories.DoesNotExist:
        context = {'info': "删除失败：类别不存在！"}
    except Exception as err:
        print(f"删除类别错误: {err}")  # 查看控制台输出的具体错误
        context = {'info': "删除失败：发生未知错误！"}
    return render(request, "myadmin/info.html", context)